var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var Pagination = require('../../common/pagination/index.js');
var app = getApp();

Page(common.extendPage(PageBase, {
    data: {
        dataLoaded: false,
    },

    onLoad(options) {

        common.initApp({
            extSuc: () => {
                this._getList();
            },
            loginSuc: () => {
                this.$loginSuc();
            },
            sysInfoSuc: (sysInfo) => {
                this.setData({
                    winHei: app.getWinHei(),
                });
            },
        });
    },

    onShareAppMessage: function(res) {
        return {
            title: app.getMarketTitle(),
            path: '/pages/couponList/index',
            success: function(res) {
                // 转发成功
            },
            fail: function(res) {
                // 转发失败
            }
        }
    },

    onPullDownRefresh() {
        this._pagination && this._pagination.flush(() => {
            wx.stopPullDownRefresh();
        });
    },

    onReachBottom() {
        this._pagination && this._pagination.loadNext();
    },

    /**
     * 获取优惠券列表
     * @return {[type]} [description]
     */
    _getList() {
        this._pagination = new Pagination({
            page: this,
            scope: 'pagination'
        }).init({
            rendData: (page, cb) => {

                ajax.G({
                    url: '/market/Coupon/getCouponCfg',
                    data: {
                        page,
                    },
                    success: (res) => {
                        var {
                            couponList = []
                        } = res.result;
                        var allList = this.data.couponList || [];

                        this.setData({
                            dataLoaded: true,
                            couponList: page == 1 ? couponList : allList.concat(couponList)
                        });

                        cb && cb(couponList.length);
                    }
                });
            }
        });
    },

    /**
     * 领取优惠券
     * @param  {[type]} evt [description]
     * @return {[type]}     [description]
     */
    drawCoupon(evt) {
        ajax.P({
            url: '/market/Coupon/activeCoupon',
            data: {
                coupon_cfg_id: evt.currentTarget.dataset.couponId
            },
            success: (res) => {

                util.alert('领取成功', () => {
                    this._pagination && this._pagination.flush();
                });

            }
        });
    }
}));